<?php


namespace app\common\model;


use ke\Model;

class Config extends Model
{
    protected $type = [
        'id'=>'integer',
        'sort'=>'integer'
    ];
    protected $json = [
        'options',
        'extends'
    ];


    /**
     * 解析value
     * @param bool $read 是否读取
     * @param mixed $value 值
     * @param string $type 数据类型
     * @return mixed
     */
    private function parseValue(bool $read, $value, $type)
    {
        switch ($type) {
            case 'int':
                $value = intval($value);
                break;
            case 'json':
                $value = $read ? json_decode($value, true) : json_encode($value);
                break;
            default:
                break;
        }

        return $value;
    }


    public function setValueAttr($data)
    {
        $d = $this->getData();
        if (isset($d['data_type'])) {
            if (isset($d['component']) && $d['component'] === 'checkbox') {
                $data = json_encode(array_map(function ($item) use($d) {
                    return $this->parseValue(true, $item, $d['data_type']);
                }, $data));
            } else {
                $data = $this->parseValue(false, $data, $d['data_type']);
            }
        }

        return $data;
    }


    public function getValueAttr()
    {
        $d = $this->getData();
        $data = $d['value'];
        if (isset($d['data_type'])) {
            if (isset($d['component']) && $d['component'] === 'checkbox') {
                $data = array_map(function ($item) use($d) {
                    return $this->parseValue(true, $item, $d['data_type']);
                }, json_decode($data, true));
            } else {
                $data = $this->parseValue(true, $data, $d['data_type']);
            }
        }

        return $data;
    }


    public function getOptionsAttr()
    {
        $options = $this->getData('options');
        $type = $this->getData('data_type');

        if ($options) {
            $options = array_map(function ($item) use($type) {
                if ($item instanceof \stdClass) {
                    $item->value = $this->parseValue(true, $item->value, $type);
                } else {
                    $item['value'] = $this->parseValue(true, $item['value'], $type);
                }
                return $item;
            }, $options);
        }
        return $options;
    }


    public function setOptionsAttr($options)
    {
        $type = $this->getData('data_type');

        if ($options) {
            $options = array_map(function ($item) use($type) {
                $item['value'] = $this->parseValue(true, $item['value'], $type);
                return $item;
            }, $options);
        }
        return $options;
    }
}
